<?php

namespace App\Http\Controllers\Home;

use App\Models\ActivityCategorys;
use App\Models\Activitys;
use App\Models\Areas;
use App\Models\Buys;
use App\Models\Categorys;
use App\Models\Collections;
use App\Models\Configs;
use App\Models\Footprints;
use App\Models\IntegralLogs;
use App\Models\SignUps;
use App\Models\Stores;
use App\Models\UserInfos;
use App\Models\Users;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ActivityController extends Controller
{
    /**
     * 供应商发布活动页面
     * @param url home.activity.actAdd
     * @param Request $request
     * @return bool
     */
    public function actAdd(Request $request){
        $user_id = auth()->guard('web')->id();
        $userinfo = Users::where('id',$user_id)->value('status');
        if(empty($user_id) || empty($userinfo)){
            return redirect(route('home.login.login'));
        }else{
            return view('home.activity.add');
        }
    }
    /**
     * 供应商发布活动
     * @param url home.activity.actAddApi
     * @param Request $request
     * @param user_id 发布人id
     * @param thumb 活动封面图
     * @param title 需求标题
     * @param cate_pid 一级分类id
     * @param cate_id 二级分类id
     * @param content 需求描述
     * @param area 区域
     * @param limit 人数限制
     * @param cost 费用（0为免费活动）
     * @param place 地址
     * @param view 浏览量
     * @param link_name 联系人
     * @param link_phone 联系人电话
     * @param link_department 联系人部门
     * @param link_position 联系人职位
     * @param enroll_at 报名截止时间
     * @param start_at 活动开始时间
     * @return bool
     */
    public function actAddApi(Request $request){
        try{
            $user_id = auth()->guard('web')->id();//获取当前登录用户
            if (empty($user_id)) return $this->writeJson(1,null,'请先登录');
            $userinfo = Users::where(['id'=>$user_id, 'status'=>1])->value('type');
            if (empty($userinfo)) return $this->writeJson(1,null,'用户不存在');
            if($userinfo != 2)  return $this->writeJson(1,null,'HR不能发布活动');
            $store = Stores::where(['user_id'=>$user_id, 'status'=>1])->where('status','<>',-1)->value('store_name');
            if (empty($store)) return $this->writeJson(1,null,'请先开店');
            $params = [
                'user_id' => $user_id,
                'sponsor' => $store,
                'thumb' =>  (string)$request->post('thumb'),
                'title' => (string)$request->post('title'),
                'cate_pid' => (int)$request->post('cate_pid'),
                'cate_id' => (int)$request->post('cate_id'),
                'content' => (string)$request->post('content'),
                'area' => (int)$request->post('area'),
                'limit' => (int)$request->post('limit'),
                'cost' => (string)$request->post('cost'),
                'place' => (string)$request->post('place'),
                'view' => (int)$request->post('view'),
                'link_name' => (string)$request->post('link_name'),
                'link_phone' => (string)$request->post('link_phone'),
                'link_department' => (string)$request->post('link_department'),
                'link_position' => (string)$request->post('link_position'),
                'enroll_at' => (string)$request->post('enroll_at'),
                'start_at' => (string)$request->post('start_at'),
//                'end_at' => (string)$request->post('end_at'),
                'source' => 2,
            ];
            $params['charge'] = $params['cost'] == 0 ? 2 : 1;
            if(!preg_match('/^((13|14|15|16|17|18)[0-9]\d{8})$/', $params['link_phone']))   return $this->writeJson(1,null,'请填写正确的手机号码');
            Activitys::create($params);
            return $this->writeJson(0, null, '发布成功,请等待平台审核!');
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 发布活动右侧热门活动
     * @param url home.activity.addRightHotActApi
     * @param Request $request
     * @param hot 是否热门：1否 2是(用于活动报名页面-右侧热门活动)
     * @param cid 活动一级分类id(用于活动详情-该类型推荐活动)
     * @return bool
     * @return act_state 活动状态
     */
    public function addRightHotActApi(Request $request)
    {
        try{
            $params = [
                'hot'=>(int)$request->get('hot'),
                'cid' => (int)$request->get('cid',0),//活动一级分类id
                'status' => 1,
            ];
            $now_time = date('Y-m-d H:i:s');
            $fields = ['id','thumb','title','cate_pid','cate_id','view','cost','number','enroll_at','start_at'];
            $lists = Activitys::allLists($params,$fields, null,5);
            foreach ($lists as $K=>$v){
                $lists[$K]['view'] = strlen($v['view'])>=4 ? '999+' : $v['view'];
                $lists[$K]['number'] = strlen($v['number'])>=4 ? '999+' : $v['number'];
                $lists[$K]['start_at'] = trim(@date('Y-m-d', strtotime($v['start_at'])));
                $lists[$K]['enroll_at'] = trim(@date('Y-m-d', strtotime($v['enroll_at'])));
                if($now_time <= $v['enroll_at']){
                    $lists[$K]['act_state'] = '报名中';
                }elseif ($now_time >= $v['start_at']){
                    $lists[$K]['act_state'] = '已举办';
                }else {
                    $lists[$K]['act_state'] = '报名结束';
                }
            }
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 活动分类页面
     * @param url home.activity.actCate
     * @param Request $request
     * @return bool
     */
    public function actCate(){
        return view('home.activity.cate');
    }
    /**
     * 活动分类
     * @param url home.activity.actCatesApi
     * @param Request $request
     * @return bool
     * @return sponsor 主办方
     * @return cost 费用
     * @return number 报名人数
     * @return limit 人数限制
     * @return enroll_at 报名截止时间
     * @return start_at 活动开始时间
     * @return $lists['act_hot']热门活动  $lists['act_new']最新活动
     */
    public function actCatesApi(Request $request)
    {
        try{
            $now_time = date('Y-m-d H:i:s');
            $lists = [];
            $lists['act_cate'] = ActivityCategorys::getCascaderList();
            $lists['act_hot'] = Activitys::allLists(['hot'=>2,'status'=>1],['*'], null,3);
            $lists['act_new'] = Activitys::allLists(['status'=>1],['*'], null,3);
            foreach ($lists['act_cate'] as $key=>$val){
                $lists['act_cate'][$key]['bool'] = false;
            }
            foreach ($lists['act_hot'] as $key=>$val){
                $lists['act_hot'][$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
                $lists['act_hot'][$key]['number'] = strlen($val['number'])>=4 ? '999+' : $val['number'];
                if($now_time <= $val['enroll_at']){
                    $lists['act_hot'][$key]['act_state'] = '报名中';
                }elseif ($now_time >= $val['start_at']){
                    $lists['act_hot'][$key]['act_state'] = '已举办';
                }else {
                    $lists['act_hot'][$key]['act_state'] = '报名结束';
                }
            }
            foreach ($lists['act_new'] as $key=>$val){
                $lists['act_new'][$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
                $lists['act_new'][$key]['number'] = strlen($val['number'])>=4 ? '999+' : $val['number'];
                if($now_time <= $val['enroll_at']){
                    $lists['act_new'][$key]['act_state'] = '报名中';
                }elseif ($now_time >= $val['start_at']){
                    $lists['act_new'][$key]['act_state'] = '已举办';
                }else {
                    $lists['act_new'][$key]['act_state'] = '报名结束';
                }
            }
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 活动列表页面
     * @param url home.activity.actList
     * @param Request $request
     * @return bool
     */
    public function actList(){
        return view('home.activity.list');
    }
    /**
     * 活动列表
     * @param url home.activity.actListsApi
     * @param Request $request
     * @param cid 一级分类id
     * @param cid_id 二级分类id
     * @param area 区域id
     * @param charge 是否收费 1：收费 2：免费
     * @param act_state 活动状态 1：报名中 2：已举办
     * @param page 页码
     * @param sid 排序id 1:浏览量 2:活动时间 3:报名数 4:价格  不传或其他值：创建时间
     * @param orderby 'desc'倒叙 ‘asc'正序
     * @return bool
     * @return （array）children 二级分类
     * @return （array）act 活动列表
     * @return （array）area 区域
     */
    public function actListsApi(Request $request)
    {
        try{
            $now_time = date('Y-m-d H:i:s');
            $map = [
                'cid' => (int)$request->get('cid'),//一级分类id
                'cid_id' => $request->get('cid_id'),//二级分类id
                'area' => (int)$request->get('area'),
                'charge' => (int)$request->get('charge'),
                'status' => 1,
            ];
            if (!empty($map['cid_id'])){
                $map['cid_id'] = explode(",", $map['cid_id']);
            }

            $act_state = (int)$request->get('act_state');//活动状态
            if($act_state == 1){
                $map['enroll_at'] = $now_time;
            }elseif ($act_state == 2){
                $map['start_at'] = $now_time;
            }
            $page = (int)$request->get('page',1);//页码
            $sid = (int)$request->get('sid');//排序
            $orderby = (string)$request->get('orderby','desc');//排序
            if ($sid == 1){
                $sort = 'view';
            }elseif ($sid == 2){
                $sort = 'start_at';
            }elseif ($sid == 3){
                $sort = 'number';
            }elseif ($sid == 4){
                $sort = 'cost';
            }else{
                $sort = 'created_at';
            }
            $lists = [];
            $lists['cate_id'] = ActivityCategorys::getcates(['pid'=>0],['id','name','pid']);//一级分类
            //二级分类
            if(empty($map['cid'])){
                $lists['children'] = ActivityCategorys::where('pid','<>','0')->where('status','<>',-1)->get(['id','name','pid']);
            }else{
                $lists['children'] = ActivityCategorys::getcates(['pid'=>$map['cid']],['id','name','pid']);
            }
            $lists['act'] = Activitys::allLists($map, $fields=['*'], $page, 10, $sort, $orderby);
            foreach ($lists['act'] as $key=>$val){
                $lists['act'][$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
                $lists['act'][$key]['number'] = strlen($val['number'])>=4 ? '999+' : $val['number'];
                if($now_time <= $val['enroll_at']){
                    $lists['act'][$key]['act_state'] = '报名中';
                }elseif ($now_time >= $val['start_at']){
                    $lists['act'][$key]['act_state'] = '已举办';
                }else{
                    $lists['act'][$key]['act_state'] = '报名结束';
                }
            }
            $lists['area'] = Areas::get(['id','name','pid']);//服务区域

            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 活动详情页面
     * @param url home.activity.actDetails
     * @param Request $request
     * @return bool
     */
    public function actDetails(){
        return view('home.activity.details');
    }
    /**
     * 活动详情
     * @param url home.activity.actDetailsApi
     * @param Request $request
     * @param id 活动id
     * @return bool
     * @return is_collect 1:未收藏 2:已收藏
     * @return is_sign_up 1:未报名 2:已报名
     * @return is_act 1:可报名 2:不可报名
     * @return (array)store 主办方信息
     * @return store_collect 店铺1:未收藏 2:已收藏
     */
    public function actDetailsApi(Request $request){
        try{
            $id = (int)$request->get('id',0);//活动id
            if (empty($id)) return $this->writeJson(1,null,'参数错误');
            $now_time = date('Y-m-d H:i:s');
            $lists = Activitys::details(['id'=>$id], ['*']);
            $lists['view'] = strlen($lists['view'])>=4 ? '999+' : $lists['view'];
            $lists['number'] = strlen($lists['number'])>=4 ? '999+' : $lists['number'];
            $lists['is_act'] = 1;//默认可报名
            if($now_time <= $lists['enroll_at']){
                $lists['act_state'] = '报名中';
                $lists['is_act'] = 1;//可报名
            }elseif ($now_time >= $lists['start_at']){
                $lists['act_state'] = '已举办';
                $lists['is_act'] = 2;//不可报名
            }else{
                $lists['act_state'] = '报名结束';
                $lists['is_act'] = 2;//不可报名
            }
            //判断是否收藏和报名
            $userinfo = auth()->guard('web')->user();//获取当前登录用户
            $lists['is_collect'] = 1;//默认未收藏
            $lists['is_sign_up'] = 1;//默认未报名
            if (!empty($userinfo)){
                if($userinfo['type'] == 1){
                    //收藏
                    $collect = Collections::where(['collect_id'=>$id,'user_id'=>$userinfo['id'],'type'=>5])->value('collect_id');
                    $lists['is_collect'] = empty($collect) ? 1 : 2;
                    //报名
                    $sign_up = SignUps::where(['activity_id'=>$id, 'user_id'=>$userinfo['id']])->where('status','<>',-1)->value('activity_id');
                    $lists['is_sign_up'] = empty($sign_up) ? 1 : 2;
                }
                //添加足迹
                $foot_arr = [
                    'user_id' => $userinfo['id'],
                    'foot_id' => $id,
                    'type'    => 4,
                ];
                Footprints::create($foot_arr);
            }
            //主办方信息
            if($lists['source'] == 1){
                $base = Configs::getConfig('base');
                $lists['store'] = ['logo'=>$base['site_logo'], 'name'=>$lists['sponsor']];
            }else if ($lists['source'] == 2){
                $fields = ['id','store_name','logo','cate_id','call','credit','collections','area_info','hot','quality'];
                $store = Stores::details(['id'=>$lists['user_id']], $fields);
                $store['call'] = strlen($store['call'])>=4 ? '999+' : $store['call'];
                //二级分类
                $store['cate_id'] = explode(',',$store['cate_id']);
                foreach ($store['cate_id'] as $k => $v){
                    $pidTree[] =Categorys::where('id',$v)->first('name');
                }
                $store['cate_id'] = $pidTree;
                //判断是否收藏
                $store['store_collect'] = 1;//默认未收藏
                if (!empty($userinfo) && $userinfo['type'] == 1){
                    $collect = Collections::where(['collect_id'=>$id,'user_id'=>$userinfo['id'],'type'=>4])->value('collect_id');
                    $store['store_collect'] = empty($collect) ? 1 : 2;
                }
                $lists['store'] = $store;
            }
            Activitys::where('id',$id)->increment('view');//浏览量加1
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 活动详情右侧同类型热门活动
     * @param url home.activity.detailsRightHotActApi
     * @param Request $request
     * @param cid 活动一级分类id(用于活动详情-该类型推荐活动)
     * @return bool
     * @return act_state 活动状态
     */
    public function detailsRightHotActApi(Request $request)
    {
        try{
            $params = [
                'cid' => (int)$request->get('cid',0),//活动一级分类id
                'status' => 1,
//                'enroll_at' => date('Y-m-d H:i:s'),
            ];
            $now_time = date('Y-m-d H:i:s');
            $fields = ['id','thumb','title','cate_pid','cate_id','view','cost','limit','number','enroll_at','start_at'];
            $lists = Activitys::allLists($params,$fields, null,5,'charge');
            foreach ($lists as $K=>$v){
                $lists[$K]['view'] = strlen($v['view'])>=4 ? '999+' : $v['view'];
                $lists[$K]['number'] = strlen($v['number'])>=4 ? '999+' : $v['number'];
                $lists[$K]['start_at'] = trim(@date('Y-m-d', strtotime($v['start_at'])));
                if($now_time <= $v['enroll_at']){
                    $lists[$K]['act_state'] = '报名中';
                }elseif ($now_time >= $v['start_at']){
                    $lists[$K]['act_state'] = '已举办';
                }else{
                    $lists[$K]['act_state'] = '报名结束';
                }
            }
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 活动收藏
     * @param url home.activity.actCollectApi
     * @param Request $request
     * @param collect_id 收藏内容id
     * @return bool
     */
    public function actCollectApi(Request $request){
        try{
            $user_id = auth()->guard('web')->id();
            if (empty($user_id)) return $this->writeJson(1,null,'请先登录');
            $collect_id = (int)$request->post('collect_id');
            if (empty($collect_id)) return $this->writeJson(1,null,'参数错误');
            $userinfo = Users::where(['id'=>$user_id, 'status'=>1])->value('type');
            if (empty($userinfo)) return $this->writeJson(1,null,'用户不存在');
            if ($userinfo != 1) return $this->writeJson(1,null,'供应商不能收藏');
            $collect = Collections::where(['collect_id'=>$collect_id, 'user_id'=>$user_id, 'type'=>5])->value('id');
            if (empty($collect)){
                $params = [
                    'collect_id' => $collect_id,
                    'user_id' => $user_id,
                    'collect_at' => date('Y-m-d H:i:s'),
                    'type' => 5,
                ];
                Collections::create($params);
                Activitys::where('id',$collect_id)->increment('collect');
                return $this->writeJson(0, null, '收藏成功');
            }else {
                Collections::where(['collect_id'=>$collect_id, 'user_id'=>$user_id, 'type'=>5])->delete();
                return $this->writeJson(0, null, '取消收藏成功');
            }
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * HR报名活动数据
     * @param url home.activity.actSignUpDataApi
     * @return username 用户名
     * @return sex 性别 1男 2女
     * @return mobile 电话
     * @return email 邮箱
     * @return (array)user_info 具体信息
     * @return company_name 公司名称
     * @return hr_department 部门
     * @return hr_position 职位
     * @return company_type 公司类型
     * @return company_industry 公司行业
     * @return company_size 员工人数
     * @return hr_size 部门规模
     */
    public function actSignUpDataApi(Request $request){
        try{
            $user_id = auth()->guard('web')->id();
            if (empty($user_id)) return $this->writeJson(1,null,'请先登录');
            $fields = ['id','username','sex','mobile','email','type'];
            $userinfo = Users::getUserInfo(['id'=>$user_id],$fields);
            if (empty($userinfo)) return $this->writeJson(1,null,'用户不存在');
            if ($userinfo['type'] != 1) return $this->writeJson(1,null,'供应商不能报名活动');

            return $this->writeJson(0, $userinfo);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * HR报名活动
     * @param url home.activity.actSignUpApi
     * @param Request $request
     * @param activity_id 活动id
     * @param user_name 姓名
     * @param sex 性别 1:男 2:女
     * @param phone 电话
     * @param email 邮箱
     * @param company 公司
     * @param department 部门
     * @param position 职位
     * @param type 类型
     * @param industry 行业
     * @param size 公司人数
     * @param hr_size 部门人数
     * @param number 报名人数
     * @param money 总价
     * @param price 单价
     * @return bool
     */
    public function actSignUpApi(Request $request){
        try{
            $user_id = auth()->guard('web')->id();
            if (empty($user_id)) return $this->writeJson(1,null,'请登录');
            $user_info = Users::where(['id'=>$user_id, 'status'=>1])->first(['username','type']);
            if (empty($user_info)) return $this->writeJson(1,null,'用户不存在');
            if($user_info['type'] != 1)  return $this->writeJson(1,null,'供应商不能报名活动');

            $activity_id = (int)$request->post('activity_id');
            if (empty($activity_id)) return $this->writeJson(1,null,'参数错误');
            $act = Activitys::where('id',$activity_id)->where('status','<>',-1)->first(['id','cost','charge']);
            if (empty($act)) return $this->writeJson(1,null,'此活动不存在');
            $sign_up = SignUps::where(['user_id'=>$user_id,'activity_id'=>$activity_id])->value('id');
            if (!empty($sign_up)) return $this->writeJson(1,null,'您已报名此活动');

            $params = [
                'pay_sn' => Buys::makePaySn($user_id),
                'activity_id' => $activity_id,
                'user_id' => $user_id,
                'user_name' => (string)$request->post('user_name'),
                'sex' => (int)$request->post('sex'),
                'phone' => (string)$request->post('phone'),
                'email' => (string)$request->post('email'),
                'company' => (string)$request->post('company'),
                'department' => (string)$request->post('department'),
                'position' => (string)$request->post('position'),
                'type' => (int)$request->post('type'),
                'industry' => (int)$request->post('industry'),
                'size' => (int)$request->post('size'),
                'hr_size' => (int)$request->post('hr_size'),
                'number' => (int)$request->post('number'),
                'price' => $act['cost'],
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ];
            if($act['charge'] == 2){
                $params['charge'] = 2;
                $params['pay_state'] = 2;
                $params['pay_at'] = date('Y-m-d H:i:s');
                Activitys::where('id',$params['activity_id'])->increment('number');//报名人数加1
            }else{
                $params['money'] = $params['price'] * $params['number'];
                $params['charge'] = 1;
                $params['pay_state'] = 1;
            }
            $sign_up_id = SignUps::insertGetId($params);
            $integral = Configs::getConfig('integral');
            Users::where('id',$user_id)->increment('integral',$integral['hr_activity']);//报名活动送积分
            //添加日志记录
            $integral = [
                'user_id' => $user_id,
                'user_name' => $user_info['username'],
                'integral' => '+'.$integral['hr_activity'],
                'desc' => '报名活动送积分',
                'type' => 1,
            ];
            IntegralLogs::create($integral);
            if($act['charge'] == 2){
                return $this->writeJson(0, null, '报名成功');
            }else{
                return $this->writeJson(0, $sign_up_id, '立即支付');
            }
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 活动支付页面
     * @param url home.activity.actPay
     * @param Request $request
     * @return bool
     */
    public function actPay(){
        return view('home.activity.actpay');
    }
    /**
     * 活动支付数据
     * @param url home.activity.actPayDataApi
     * @param Request $request
     * @param sign_up_id 活动订单id
     * @return bool
     * @return pay_sn 订单号
     * @return number 报名人数
     * @return money 总价
     * @return price 单价
     * @return (array)activity 活动信息
     * @return activity.title 活动名称
     * @return activity.sponsor 主办方
     */
    public function actPayDataApi(Request $request){
        try{
            $user_id = auth()->guard('web')->id();
            $sign_up_id = (int)$request->get('sign_up_id');//活动订单id
            if (empty($user_id) || empty($sign_up_id)) return $this->writeJson(1,null,'参数错误');
            $userinfo = Users::where(['id'=>$user_id, 'status'=>1])->value('type');
            if (empty($userinfo)) return $this->writeJson(1,null,'用户不存在');
            $lists = SignUps::details(['id'=>$sign_up_id, 'user_id'=>$user_id], $fields=['*']);
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 活动支付
     * @param url home.activity.actCompleteOrder
     * @param pay_order 支付单号
     */
    public function actCompleteOrder(Request $request){
        try{
            //根据订单信息，生成支付二维码
            $pay_order = $request->post('pay_order');//活动订单单号
            $order_info = SignUps::where(array('pay_sn'=>$pay_order))->first();
            $order_act = Activitys::where(array('id'=>$order_info['activity_id']))->first();
            $detail = $order_act['title'].'支付订单';
            $notify_url = route('home.payment.actNotifyUrl');
            $payment = new PaymentController();
            $ret=$payment->wxPayment($pay_order, $order_info['activity_id'],$order_info['money'],'支付订单',$detail,$notify_url);

            if($ret['code'] == 1){
                return $this->writeJson(0,$ret['data']);
            }else{
                return $this->writeJson(1,$ret);
            }
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 活动支付后页面
     * @param url home.activity.actPayAfter
     * @param Request $request
     * @return bool
     */
    public function actPayAfter(){
        return view('home.activity.actpay_after');
    }




}